package com.bjx.flow.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.bjx.common.core.exception.BJXException;
import com.bjx.common.security.util.LoginUtil;
import com.bjx.flow.domain.vo.FlowDisposeVO;
import com.bjx.flow.service.ITaskDisposeService;
import lombok.extern.slf4j.Slf4j;
import org.camunda.bpm.engine.*;
import org.camunda.bpm.engine.history.HistoricActivityInstance;
import org.camunda.bpm.engine.history.HistoricTaskInstance;
import org.camunda.bpm.engine.impl.RepositoryServiceImpl;
import org.camunda.bpm.engine.impl.persistence.entity.ProcessDefinitionEntity;
import org.camunda.bpm.engine.impl.pvm.process.ActivityImpl;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;

/**
 * @desc: 任务处理具体实现
 * @author: liushuai
 * @date: 2023/1/5 13:35
 */
@Slf4j
@Service
public class TaskDisposeServiceImpl implements ITaskDisposeService {
    @Resource
    private TaskService taskService;
    @Resource
    private IdentityService identityService;
    @Resource
    private HistoryService historyService;
    @Resource
    private RuntimeService runtimeService;
    @Resource
    private RepositoryService repositoryService;

    @Override
    public void pass(FlowDisposeVO disposeVO) {
        // 添加审批人
       // identityService.setAuthenticatedUserId(LoginUtil.loginInfo().getUserId());
        if(StrUtil.isNotEmpty(disposeVO.getComment())){
            taskService.createComment(disposeVO.getTaskId(), disposeVO.getProcessInstanceId(), disposeVO.getComment());
        }
        if(disposeVO.getVariables() == null){
            disposeVO.setVariables(new HashMap<>());
        }
        taskService.complete(disposeVO.getTaskId(),disposeVO.getVariables());
    }

    @Override
    public void reject(FlowDisposeVO disposeVO) {
        // 添加审批人
        identityService.setAuthenticatedUserId(LoginUtil.loginInfo().getUserId());
        // 获取当前任务，未办理任务id
        HistoricTaskInstance currTask = historyService.createHistoricTaskInstanceQuery()
                .taskId(disposeVO.getTaskId())
                .singleResult();
        if (ObjectUtil.isNull(currTask)) {
            log.error("没有查询到审批任务:{}",disposeVO.getTaskId());
            throw new BJXException("没有查询到审批任务");
        }
        //获取流程定义
        ProcessDefinitionEntity processDefinitionEntity = (ProcessDefinitionEntity) ((RepositoryServiceImpl) repositoryService)
                .getDeployedProcessDefinition(currTask.getProcessDefinitionId());
        if(StrUtil.isNotEmpty(disposeVO.getComment())){
            taskService.createComment(disposeVO.getTaskId(), disposeVO.getProcessInstanceId(), disposeVO.getComment());
        }
        ActivityImpl currentActivity = (processDefinitionEntity).findActivity(currTask.getTaskDefinitionKey());
        // 获取起始活动
        List<HistoricActivityInstance> historicActivityInstances = historyService.createHistoricActivityInstanceQuery()
                .activityType("userTask")
                .processInstanceId(disposeVO.getProcessInstanceId())
                .finished()
                .orderByHistoricActivityInstanceEndTime()
                .asc()
                .list();
        if(historicActivityInstances.size() == 0){
            return;
        }
        // 起始节点活动
        ActivityImpl lastActivity = processDefinitionEntity.findActivity(historicActivityInstances.get(0).getActivityId());

        // 退回至起点申请人
        runtimeService.createProcessInstanceModification(disposeVO.getProcessInstanceId())
                // 关闭当前活动任务节点
                .cancelAllForActivity(currentActivity.getActivityId())
                .setAnnotation("驳回")
                // 启动申请人节点
                .startBeforeActivity(lastActivity.getActivityId())
                .execute();
    }

    public void sendBack(FlowDisposeVO disposeVO) {
        // 添加审批人
        identityService.setAuthenticatedUserId(LoginUtil.loginInfo().getUserId());
        // 获取当前任务，未办理任务id
        HistoricTaskInstance currTask = historyService.createHistoricTaskInstanceQuery()
                .taskId(disposeVO.getTaskId())
                .singleResult();
        if (ObjectUtil.isNull(currTask)) {
            log.error("没有查询到审批任务:{}",disposeVO.getTaskId());
            throw new BJXException("没有查询到审批任务");
        }
        //获取流程定义
        ProcessDefinitionEntity processDefinitionEntity = (ProcessDefinitionEntity) ((RepositoryServiceImpl) repositoryService)
                .getDeployedProcessDefinition(currTask.getProcessDefinitionId());
        if(StrUtil.isNotEmpty(disposeVO.getComment())){
            taskService.createComment(disposeVO.getTaskId(), disposeVO.getProcessInstanceId(), disposeVO.getComment());
        }
        ActivityImpl currentActivity = (processDefinitionEntity).findActivity(currTask.getTaskDefinitionKey());
        // 获取起始活动
        List<HistoricActivityInstance> historicActivityInstances = historyService.createHistoricActivityInstanceQuery()
                .activityType("userTask")
                .processInstanceId(disposeVO.getProcessInstanceId())
                .finished()
                .orderByHistoricActivityInstanceEndTime()
                .asc()
                .list();
        if(historicActivityInstances.size() == 0){
            return;
        }
        // 起始节点活动
        ActivityImpl lastActivity = processDefinitionEntity.findActivity(historicActivityInstances.get(0).getActivityId());

        // 退回至起点申请人
        runtimeService.createProcessInstanceModification(disposeVO.getProcessInstanceId())
                // 关闭当前活动任务节点
                .cancelAllForActivity(currentActivity.getActivityId())
                .setAnnotation("驳回")
                // 启动申请人节点
                .startBeforeActivity(lastActivity.getActivityId())
                .execute();
    }
}
